#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <strings.h>

int main(int argc,char *argv[]){

    // 参数
    if (argc != 2){
        fprintf(stderr,"Usage argc ... \n");
        exit(-1);
    }

    // 得到通信文件描述符
    int cfd = socket(PF_INET,SOCK_DGRAM,0);
    if (cfd < 0){
        fprintf(stderr,"socket error!\n");
        exit(-1);
    } 

    // 绑定端口号
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(atoi(argv[1]));
    ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(cfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)) < 0){
        fprintf(stderr,"bind error!\n");
        exit(-1);
    }
    
    // 进行通信
    struct sockaddr_in cli_addr;
    socklen_t cli_len = sizeof(cli_addr);
    bzero(&cli_addr,sizeof(cli_addr));
    int str_len;
    char buf[1024];
    while (1){
        memset(buf,'\0',sizeof(buf));
        str_len = recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr *)&cli_addr,&cli_len);
        printf("client[ip: %s port: %d] is connected!",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
        sendto(cfd,buf,str_len,0,(struct sockaddr *)&cli_addr,cli_len);
    }

    // 关闭
    close(cfd);
    return 0;
}